import React, {Component} from 'react';

import {
    View,
    Text,
    RefreshControl,
    StyleSheet,
    Image,
    FlatList,
    TouchableOpacity,
    DeviceEventEmitter,
    Dimensions,
    ScrollView, Platform, UIManager, LayoutAnimation,
} from 'react-native';
import StyleUtils from "../../res/styles/StyleUtils";
import ScrollableTabView, {ScrollableTabBar, DefaultTabBar} from 'react-native-scrollable-tab-view';
import IparNetwork, {SERVER_TYPE} from "../../httpUtils/IparNetwork";
import CommonUtils from "../../common/CommonUtils";
import I18n from '../../res/language/i18n'
import IparImageView from "../../custom/IparImageView";
import ArticleDetail from "./ArticleDetail";
import NurTreeView from "../../custom/NurTreeView";
import ArticleItem from "./item/ArticleItem";

const {width, height} = Dimensions.get('window');

export default class ArticlePageNew extends Component {

    constructor(props) {
        super(props);

        this.iparNetwork = new IparNetwork();

        this.state = {
            tabData: [],
        }
        this.isLogin = false;
    }


    componentDidMount() {
        CommonUtils.getAcyncInfo('country_iso')
            .then((country) => {
                this.country = country;
                this.getData();
            });

        CommonUtils.getAcyncInfo('userInfo')
            .then((res) => {
                this.isLogin = true;
            });

    }


    /**
     * 获取数据--》文章列表
     */
    getData() {
        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.uiAdminIpar + 'appMenuData?', 'country=' + this.country)
            .then((result) => {
                console.log(result);
                CommonUtils.dismissLoading();
                if (result.code === 200) {
                    this.setState({
                        tabData: result.data,
                    })
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ArticlePageNew--getData--error:' + error);
            });
    }

    render() {
        let {tabData} = this.state;

        return (
            <View style={[StyleUtils.flex]}>
                <ScrollableTabView
                    renderTabBar={() => <ScrollableTabBar
                        textStyle={[StyleUtils.smallFont, {}]}
                        underlineStyle={{backgroundColor: 'black', height: 1}}
                        inactiveTextColor={"gray"}
                        activeTextColor={"black"}/>}>

                    {tabData.map((item, i) => {
                        if (!item) {
                            return;
                        }
                        let _item = item.menu_lang;
                        let tabName = _item.name_zh;
                        switch (I18n.locale) {
                            case 'en':
                                tabName = _item.name_en;
                                break;
                            case 'ru':
                                tabName = _item.name_ru;
                                break;
                            case 'uy':
                                tabName = _item.name_uy;
                                break;
                        }
                        return <ArticleView
                            key={i}
                            {...this.props}
                            country={this.country}
                            cateData={item}
                            isLogin={this.isLogin}
                            tabLabel={tabName}/>
                    })}
                </ScrollableTabView>
            </View>
        );
    }
}

class ArticleView extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.lang = I18n.locale;

        this.state = {
            loading: false,
            dataSource: [],
            showCate: false,
        }
    }


    componentDidMount() {
        this.getArticleData();
    }


    /**
     * 手该语言的时候刷新页面
     */
    componentWillReceiveProps() {
        if (this.lang !== I18n.locale) {
            this.lang = I18n.locale;
            this.getArticleData();
        }
    }

    _getDefCateId(all_children_categorys) {
        if (all_children_categorys.length <= 0) return null;
        return all_children_categorys[0];
    }

    getDefCateId() {
        let cateData = this.props.cateData;

        let isFindChildren = true;
        while (isFindChildren) {
            let children = this._getDefCateId(cateData.children_app);
            if (children) {
                cateData = children;
            }
            isFindChildren = children !== null;
        }
        return cateData.cate_id;
    }

    /**
     * 获取文章数据
     */
    getArticleData() {
        if (!this.cateId) {
            this.cateId = this.getDefCateId();
        }
        this.setState({
            loading: true,
        });
        let cate_id = this.cateId.toString().replace('3', '');
        this.iparNetwork.getRequest(SERVER_TYPE.uiAdminIpar + 'artic_list?',
            'cate_id=' + cate_id + '&region=' + this.props.country + '&lang=' + I18n.locale)
            .then((result) => {
                console.log(result);
                if (result.code === 200) {
                    this.setState({
                        loading: false,
                        dataSource: result.data
                    })
                } else {
                    this.setState({
                        loading: false,
                    });
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.setState({loading: false});
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('ArticleView--getArticleData--error:' + error);
            });


    }

    /**
     * 动画效果
     */
    startAnimation() {
        if (Platform.OS === 'android') {
            UIManager.setLayoutAnimationEnabledExperimental(true);
        }
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
    }

    render() {
        let {showCate} = this.state;
        let {cateData} = this.props;
        let childrenCategorys = cateData == null ? null : cateData.children_app;

        return (
            <View style={[{flex: 1}]}>


                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.loading}
                            onRefresh={() => {
                                this.getArticleData();
                            }}
                        />
                    }>
                    <FlatList
                        style={{flex: 1}}
                        extraData={this.state}
                        keyExtractor={(item, index) => index}
                        renderItem={(item) => this.renderRow(item.item, item.index)}
                        data={this.state.dataSource}/>

                    {!this.state.loading && this.state.dataSource.length <= 0 && <View
                        style={[StyleUtils.center, {flex: 1, height: 200}]}>
                        <Text style={[StyleUtils.smallFont]}>{I18n.t('default.noData')}</Text>
                    </View>}
                </ScrollView>

                {childrenCategorys && childrenCategorys.length > 0 &&
                <View style={[{
                    height: 40,
                    width: '100%',
                    position: 'absolute',

                }, showCate && [{backgroundColor: 'rgba(255,255,255,0.9)', height: null}, StyleUtils.shadowBottom,]]}>

                    {showCate && <NurTreeView
                        data={childrenCategorys}
                        onItemClick={(item) => this.onMoreClick(item)}/>}


                    <TouchableOpacity
                        onPress={() => {
                            this.startAnimation();
                            this.setState({showCate: !showCate});
                        }}
                        style={[StyleUtils.center, {
                            backgroundColor: 'rgba(255,255,255,0.74)',
                            width: 50,
                            height: 50,
                            alignSelf: 'flex-end',
                            borderBottomLeftRadius: 10,
                        }]}>
                        <Image
                            style={{width: 24, height: 24, tintColor: 'black'}}
                            source={require('../../res/images/ic_select_category.png')}/>
                    </TouchableOpacity>
                </View>}
            </View>
        );
    }


    /**
     * 点击item
     * */
    onMoreClick(item) {
        this.cateId = item.cate_id;
        if (item.children_app.length > 0) {
            item.isOpen = !item.isOpen;
        } else {
            this.state.showCate = false;
            this.getArticleData()
        }
        this.startAnimation();
        this.setState({});
    }

    itemClickListener(data) {
        this.props.navigator.push({
            component: ArticleDetail,
            params: {
                artID: data.art_id,
                image: data.image,
                title: data.title,
            }
        })
    }

    renderRow(rowData, rowID) {
        // return (
        //     <TouchableOpacity
        //         activeOpacity={0.5}
        //         onPress={() => this.itemClickListener(rowData)}
        //         style={[styles.articleItemBox]}
        //     >
        //
        //
        //         <IparImageView
        //             borderRadius={5}
        //             resizeMode={'cover'}
        //             width={'100%'}
        //             height={width / 2.5}
        //             url={rowData.image}/>
        //
        //
        //         <View style={styles.titleBox}>
        //             <Text numberOfLines={1} style={[styles.tv, StyleUtils.smallFont, {
        //                 fontSize: 18,
        //                 color: 'black'
        //             }]}>{rowData.title}</Text>
        //             <Text numberOfLines={2} style={[styles.tv, StyleUtils.smallFont]}>{rowData.description}</Text>
        //         </View>
        //     </TouchableOpacity>
        // )
        return <ArticleItem isLogin={this.props.isLogin} navigator={this.props.navigator} itemData={rowData}/>
    }

}
